package com.inco.cloud.server2.controller;

import com.inco.cloud.common.util.SecuityUtils;
import com.inco.cloud.server2.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;


@Controller
public class UserController {

    @Autowired
    private Environment env;

//    @Autowired
//    private ConsumerTokenServices consumerTokenServices;


    //注入服务
    @Autowired
    private UserService userService;

    @Autowired
    private SecuityUtils secuityUtils;
    /**
     * 远程调用api-auth的me方法
     * @return
     */
    @ResponseBody
    @RequestMapping("/me")
    public User me() {
        return secuityUtils.getCurrentUser();
    }

    @ResponseBody
    @RequestMapping("/server-port")
    public String serverPort() {
        return env.getProperty("server.port");
    }


    /**
     * 根据appname通过注册中心获取服务的url
     * @param appName
     * @return
     */
    @ResponseBody
    @RequestMapping("/queryServer/{app-name}")
    public String queryServer(@PathVariable("app-name")String appName, HttpServletRequest request){
        //使用 LoadBalanceClient 和 RestTemolate 结合的方式来访问
        ServiceInstance serviceInstance = loadBalancerClient.choose(appName);
        String url = String.format("http://%s:%s/hello-appname",serviceInstance.getHost(),serviceInstance.getPort());
        System.out.println("request url:"+url);
        String authHeader = request.getHeader("Authorization");
        if (authHeader != null) {
            //String access_token = authHeader.replace("Bearer", "").trim();
            System.out.println("access_token :"+authHeader);

            //headers
            HttpHeaders requestHeaders = new HttpHeaders();
            requestHeaders.add("Authorization", authHeader);
            //body
            MultiValueMap<String, String> requestBody = new LinkedMultiValueMap<>();
            requestBody.add("appName",appName);
            //HttpEntity
            HttpEntity<MultiValueMap> requestEntity = new HttpEntity<MultiValueMap>(requestBody, requestHeaders);
            RestTemplate restTemplate = new RestTemplate();
            //post
            ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, requestEntity, String.class);
            return responseEntity.getBody();

        }
        return "访问失败";
    }

    /**
     * 远程调用- 根据appname通过注册中心获取服务的url
     * @param appName
     * @return
     */
    @ResponseBody
    @RequestMapping("/queryServer2/{app-name}")
    public String queryServer2(@PathVariable("app-name")String appName, HttpServletRequest request){
        return userService.helloAppName(appName);
    }

    /**
     * 添加用户
     * @param username
     * @return
     */
    @ResponseBody
    @RequestMapping("/addUser2")
    public Integer addUser2(String userId,String username){
        return userService.addUser(userId,username);
    }

    @Autowired
    private LoadBalancerClient loadBalancerClient;
    @Autowired
    private RestTemplate restTemplate;

    //实例化 RestTemplate 实例
    @Bean
    public RestTemplate restTemplate(){

        return new RestTemplate();
    }
}
